<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Api_Standard_Distributor
{
    //获取下级会员数
    public static function get_member_num($userid,$is_member=0)
    {
        //$sub_mids = Model_Fenxiao::get_sub_mids($userid,3);
        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');
        $fenxiao_level_num = $level_num == 2 ? 2 : 3;
        $sub_mids = Model_Fenxiao::get_sub_mids($userid,$fenxiao_level_num);
        $num=0;
        if(empty($sub_mids))
        {
            return 0;
        }
        if($is_member==0)
        {
            $num = DB::query(Database::SELECT,"select count(*) as num from sline_fenxiao where memberid in (".implode(',',$sub_mids).") and status=1")->execute()->get('num');
        }
        else
        {
            $sub_mids = Model_Fenxiao::get_sub_mids($userid,1);
            $num = DB::query(Database::SELECT,"select count(*) as num from sline_fenxiao where memberid in (".implode(',',$sub_mids).") and status=-1")->execute()->get('num');
        }
        return $num;

    }

    /**
     * 获取分销客户
     * @param $params
     * @return mixed
     */
    public static function get_submembers($params)
    {
        $userid = $params['userid'];
        $fxcode = $params['fxcode'];
        $keyword = $params['keyword'];
        $page = intval($params['page']);
        $page = $page<1?1:$page;
        $pagesize = 10;
        $offset = ($page-1)*$pagesize;
        $w = " where a.fxpcode='".$fxcode."' and a.status='-1' ";
        if(!empty($keyword))
        {
            $w.= " and (c.nickname like '%{$keyword}%' or c.mobile like '%{$keyword}%' or c.email like '%{$keyword}%') ";
        }
        $order_by = " order by a.fxjointime desc ";
        $sql = "select a.memberid,a.fxjointime,a.fxrankid,b.total from sline_fenxiao a inner join sline_member c on a.memberid=c.mid
        left join (select sum(amount) as total,fxmemberid from sline_fenxiao_record where memberid=".$userid." and type=0 group by fxmemberid) b
        on a.memberid=b.fxmemberid {$w} {$order_by} limit {$offset},{$pagesize}";
        $list = DB::query(Database::SELECT,$sql)->execute()->as_array();
        foreach($list as &$row)
        {
            $member_info = Model_Member::get_member_byid($row['memberid']);
            $row['nickname'] = $member_info['nickname'];
            $row['litpic'] = Model_Api_Standard_System::reorganized_resource_url($member_info['litpic']);
            $row['account'] = empty($member_info['mobile'])?$member_info['email']:$member_info['mobile'];
        }
        return $list;

    }

    /**
     * 获取我的下级分销商列表
     * @return mixed
     */
    public static function get_subfx($params)
    {
        $group = $params['group'];
        $userid = $params['userid'];
        $order = $params['order'];
        $keyword = $params['keyword'];

        $page = intval($params['page']);
        $page = $page<1?1:$page;
        $pagesize = 10;
        $offset = ($page-1)*$pagesize;

        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');
        $fenxiao_level_num = $level_num == 2 ? 2 : 3;
        
        //$sub_mids = Model_Fenxiao::get_sub_mids($userid,3);
        $sub_mids = Model_Fenxiao::get_sub_mids($userid,$fenxiao_level_num);
        $first_sub_mids = Model_Fenxiao::get_sub_mids($userid, 1);
        if($group)
        {
            $sub_mids = Model_Fenxiao::get_sub_mids($userid, $group,true);
        }

        if(empty($sub_mids))
        {
            return array();
        }

        $order_by = "";
        switch($order)
        {
            case 1:
                $order_by = " order by ifnull(b.total,0) desc ";
                break;
            case 2:
                $order_by = " order by ifnull(b.total,0) asc ";
                break;
            case 3:
                $order_by = " order by a.fxjointime desc ";
                break;
            case 4:
                $order_by = " order by a.fxrankid desc ";
                break;
        }

        $w  = " where a.status=1 and a.memberid in (".implode(',',$sub_mids).")";
        if(!empty($keyword))
        {
            $w.= " and (c.nickname like '%{$keyword}%' or c.mobile like '%{$keyword}%' or c.email like '%{$keyword}%') ";
        }

        $sql = "select a.memberid,a.fxjointime,a.fxrankid,b.total from sline_fenxiao a
inner join sline_member c on a.memberid=c.mid
left join (select sum(amount) as total,fxmemberid from sline_fenxiao_record where memberid=".$userid." and type=0 group by fxmemberid) b on a.memberid=b.fxmemberid {$w} {$order_by} limit {$offset},{$pagesize}";

        $list = DB::query(Database::SELECT,$sql)->execute()->as_array();
        foreach($list as &$row)
        {
            $member_info = Model_Member::get_member_byid($row['memberid']);
            $row['nickname'] = $member_info['nickname'];
            $row['litpic'] = Model_Api_Standard_System::reorganized_resource_url($member_info['litpic']);
            $row['fxrank_name'] = Model_Fenxiao_Rank::get_name($row['fxrankid']);
            $row['sub_num'] = count(Model_Fenxiao::get_sub_mids($row['memberid'],1));
            $row['fxjointime'] = date('Y-m-d',$row['fxjointime']);
            $row['account'] = empty($member_info['mobile'])?$member_info['email']:$member_info['mobile'];
            $row['sub_level'] = Model_Fenxiao::get_rank($userid,$row['memberid']);
            $row['total'] = empty($row['total'])?0:$row['total'];
            $row['total'] = round($row['total'],2);

        }
        return $list;
    }
    public static  function get_products2($params)
    {
        $typeid = intval($params['typeid']);
        $userid = intval($params['userid']);
        $keyword = $params['keyword'];
        $ordertype = $params['ordertype'];
        $pagesize = 100;
        $offset = $params['offset'];
        $number = intval($params['number']);

        //分销分组ID
        $fxgroupid = DB::select('fxgroupid')->from('fenxiao')->where("memberid",'=',$userid)->execute()->get('fxgroupid');

        $result = self::search_products2(array('typeid'=>$typeid,'ordertype'=>$ordertype,'groupid'=>$fxgroupid),$keyword,$offset,$pagesize);
        $list = $result['list'];

        $list_new = array();
        $last_index = $offset;

        foreach($list as $key=>$v)
        {
            $commission_type=Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$v['typeid'],$fxgroupid);
            $v['commission_type'] = $commission_type;
            $min_price = self::get_price($v['typeid'],$v['tid']);
            $v['price'] = empty($v['price'])?0:$v['price'];
            $min_price = is_array($min_price)?$min_price['price']:$min_price;
            $min_price = empty($min_price)?0:$min_price;
            $v['price'] = !empty($min_price)?$min_price:$v['price'];

            if($commission_type==1)
            {
                $commission_rate = Model_Fenxiao::get_commission_rate($v['typeid'],$v['tid'],$fxgroupid);
                $v['commission'] =$commission_rate[0]*100;
                $v['commission'] = empty($v['commission'])?0:$v['commission'];
                $v['commission'] .='%';
                $v['profit'] = $v['price']*$commission_rate[0];
            }
            else if($commission_type==2)
            {
                $commission_rate = Model_Fenxiao::get_commission_rate_platform($v['typeid'],$v['tid'],$fxgroupid);
                $v['commission'] =$commission_rate[0]*100;
                $v['commission'] = empty($v['commission'])?0:$v['commission'];
                $v['commission'] .='%';

                $temp_order = array('typeid'=>$v['typeid'],'productautoid'=>$v['tid'],'totalprice'=>$v['price'],'dingnum'=>1);
                $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                //$platform_price = $platform_price==0? $v['price']:$platform_price;
                $v['profit'] = round($platform_price*$commission_rate[0],2);
            }
            else
            {
                $commission_cash = Model_Fenxiao::get_commission_cash_line($v['typeid'],$v['tid'],$fxgroupid);
                $v['commission'] = $commission_cash[0]['adult'];
                $v['commission'] = empty($v['commission'])?0:$v['commission'];
                $v['profit'] = $v['commission'];
            }

            $v['id'] = $v['tid'];
            $v['profit'] = self::get_prospect_fenxiao_price($typeid,$v,$fxgroupid);

            $last_index = $offset+$key+1;
            if(empty($v['profit']))
            {
                continue;
            }
            if(count($list_new)==$number)
            {
                if($key<(count($list)-1))
                {
                    $last_index = $last_index-1;
                }
                break;
            }
            else
            {
                $v['litpic'] = Common::img($v['litpic']);
                $list_new[] = $v;
            }

        }
        $is_end = false;
        if(count($list)<$pagesize || empty($list))
        {
            $is_end = true;
        }
        return array('list'=>$list_new,'is_end'=>$is_end,'last_index'=>$last_index);
    }
    //获取产品，必须要有tid 和 typeid
    public static function search_products2($params,$keyword,$offset,$pagesize)
    {
        $value_arr = array();
        //编号查询
        $where = " where a.ishidden=0 ";

        if(is_numeric($keyword))
        {
            $result = St_Product::product_series($keyword,'',true);
            $where .= " AND a.id='{$result['id']}'";
        }
        else if(!empty($keyword))
        {
            //关键字查询
            $where .= " AND a.title like :keyword ";
            $value_arr[':keyword'] = '%'.$keyword.'%';
        }

        $typeid = $params['typeid'];
        $table = self::get_table($typeid);

        if(empty($table))
        {
            return array(
                'total' => 0,
                'list' => null
            );
        }

        if($table == 'model_archive')
        {
            $where.=" AND a.typeid={$typeid} ";
        }

        $order = " order by ifnull(b.displayorder,999999) asc ";
        if($params['ordertype']==1)
        {
            $order = " order by ifnull(b.displayorder,999999) asc,a.modtime desc";
        }
        $sql = " select a.title,a.supplierlist,a.litpic,a.webid,a.id as tid,a.aid,a.modtime,a.price,b.* from sline_{$table} a left join sline_fenxiao_ratio  b on a.id=b.productid and b.typeid={$typeid} and b.groupid={$params['groupid']} {$where}  and a.price>0 {$order} ";
        //$sql.= "LIMIT {$offset},{$pagesize}";
        //计算总数
        $totalSql = "SELECT count(*) as dd ".strchr($sql," FROM");
        $totalSql = str_replace(strchr($totalSql,"ORDER BY"),'', $totalSql);//去掉order by

        $totalN = DB::query(1,$totalSql)->parameters($value_arr)->execute()->as_array();
        $totalNum = $totalN[0]['dd'] ? $totalN[0]['dd'] : 0;

        $sql.= "LIMIT {$offset},{$pagesize}";

        $arr = DB::query(1,$sql)->parameters($value_arr)->execute()->as_array();
        foreach($arr as &$v)
        {
            $v['typeid'] = $typeid;
            $module_info = $row = ORM::factory('model',$v['typeid'])->as_array();
            // $typeid = $v['typeid']<10 ? '0'.$v['typeid'] : $v['typeid'];
            $v['label'] = $module_info['modulename'];//标签
            $v['producttitle'] = $v['title'];//标题
            $v['series'] = Product::product_number($v['tid'], $typeid);//编号
            //$v['url'] = $this->get_product_url($v['typeid'],$v['aid'],$v['webid']);//地址

        }
        $out = array(
            'total' => $totalNum,
            'list' => $arr
        );
        return $out;
    }

    //获取某个产品的最低价
    public static  function get_price($typeid,$productid)
    {
        $model_info = DB::select()->from('model')->where('id','=',$typeid)->execute()->current();

        $maintable = $model_info['maintable'];
        $letter_arr = explode('_',$maintable);
        foreach($letter_arr as &$letter)
        {
            $letter = ucfirst($letter);
        }
        $class_name='Model_'.implode('_',$letter_arr);
        $price = 0;
        if(class_exists($class_name)&& method_exists($class_name,'get_minprice') )
        {
            $price = call_user_func(array($class_name, 'get_minprice'),$productid);
        }
        return $price;
    }
    //获取表名
    public static  function get_table($typeid)
    {
        $model=ORM::factory('model',$typeid);
        if(!$model->loaded())
            return false;
        return $model->maintable;
    }

    //获取分销订单
    public function get_orders($params)
    {
        $rank = intval($params['rank']);
        $typeid = intval($params['typeid']);
        $status = $params['status'];
        $userid = $params['userid'];
        $order = $params['order'];
        $keyword = $params['keyword'];
        $page = intval($params['page']);
        $page = $page<1?1:$page;
        $pagesize = 10;
        $offset = ($page-1)*$pagesize;
        $sub_mids =Model_Fenxiao::get_sub_mids($userid,0);
        if(!empty($rank))
        {
            $sub_mids =Model_Fenxiao::get_sub_mids($userid,$rank,true);
        }
        if(!empty($sub_mids) && !empty($keyword))
        {

            $keyword_submids = Model_Fenxiao::get_keyword_sub_mids($keyword);
            $keyword_w = !empty($keyword_submids)? " or mid in (".implode(',',$keyword_submids).")":'';

            $sub_members = DB::query(Database::SELECT,"select mid from sline_member where mid in(".implode(',',$sub_mids).") and (mobile like '%{$keyword}%' or email like '%{$keyword}%' or nickname like '%{$keyword}%' {$keyword_w})")->execute()->as_array();
            $sub_mids = array();
            foreach($sub_members as $sub_member)
            {
                if(!empty($sub_member['mid']))
                {
                    $sub_mids[] = $sub_member['mid'];
                }
            }
        }
        if(empty($sub_mids))
        {
            return array('status'=>true,'list'=>'');
        }

        $w = " where a.memberid in (".implode(',',$sub_mids).") ";
        if(!empty($typeid))
        {
            $w.=" and a.typeid={$typeid} ";
        }

        if(!empty($status) || $status===0 || $status==='0')
        {
            $w.=" and a.status='{$status}' ";
        }

        $order_by = "";
        switch($order)
        {
            case 2:
                $order_by = " order by ifnull(b.amount,0) desc,a.addtime desc ";
                break;
            case 3:
                $order_by = " order by ifnull(b.amount,0) asc,a.addtime desc ";
                break;
            default:
                $order_by = " order by a.addtime desc";
        }
        $sql = " select a.*,b.amount as fenxiao_amount from sline_member_order a left join sline_fenxiao_record b on a.id=b.orderid and (b.memberid is null or b.memberid=".$userid.") {$w} {$order_by} limit {$offset},{$pagesize}";
        //echo $sql;exit;
        $list = DB::query(Database::SELECT,$sql)->execute()->as_array();
        foreach ($list as &$v)
        {
            $model = ORM::factory('model', $v['typeid']);
            $table = $model->maintable;
            if ($table)
            {
                $py = empty($model->correct) ? $model->pinyin : $model->correct;
                $info = ORM::factory($table, $v['productautoid'])->as_array();
                $out = $info;
                $v['litpic'] = Common::img($out['litpic']);
                $v['url'] = St_Functions::get_web_url($info['webid']) . "/{$py}/show_{$info['aid']}.html";
            }
            $v['totalprice'] = Model_Member_Order::order_total_price($v['id'],$v);

            $commission_type=Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$v['typeid'],0);
            $rank = Model_Fenxiao::get_rank($userid,$v['memberid']);
            $rank_index=$rank;
            $v['commission_type'] = $commission_type;
            $order_temp = Model_Member_Order::order_info($v['ordersn']);
            $commission_info = Model_Fenxiao::get_order_fenxiao_info($order_temp);

            if(empty($rank_index))
            {
                $v['commission_amount'] = floatval($commission_info['commission']);
            }
            else
            {
                $v['commission_amount'] = floatval($commission_info['commission'.$rank_index]);
            }

            $member_info = Model_Member::get_member_byid($v['memberid']);
            $v['member'] = $member_info;

            $parent_fenxiao = Model_Fenxiao::get_ancestor_fenxiao($v['memberid'],1);
            $v['parent_member'] = Model_Member::get_member_byid($parent_fenxiao['memberid']);

            $v['addtime'] = date('Y-m-d H:i',$v['addtime']);
            $v['fenxiao_amount'] = empty($v['fenxiao_amount'])?0:$v['fenxiao_amount'];
            $v['status_name'] = Model_Member_Order::get_status_name($v['status']);
        }
         return array('status'=>true,'list'=>$list);
    }

    //获取返佣总和
    public static  function get_total_profit($userid)
    {
        $result = DB::query(Database::SELECT,"select amount from sline_fenxiao_record where memberid='{$userid}' and type=0")->execute()->as_array();
        $amount = 0;
        foreach($result as $row)
        {
            $amount+=$row['amount'];
        }
        return $amount;
    }

    //获取已付款，但未返佣的佣金总和
    public static function get_total_unfinish_profit($userid)
    {
        $total = 0;
        $sub_orders = Model_Fenxiao::get_sub_orders($userid,0,2);
        $fenxiao = DB::select()->from('fenxiao')->where('memberid','=',$userid)->execute()->current();
        if($fenxiao['status']==1 && $fenxiao['isfrozen']!=1)
        {
            $my_orders = DB::select()->from('member_order')->where('memberid','=',$fenxiao['memberid'])->and_where('status','=',2)->execute()->as_array();
            $sub_orders = empty($sub_orders)?array():$sub_orders;
            $sub_orders = array_merge($sub_orders,$my_orders);
        }


        foreach($sub_orders  as $order)
        {
            $fenxiao_data = DB::select()->from('fenxiao_data')->where('order_id','=',$order['id'])->execute()->current();
            $order_info = Model_Member_Order::order_info($order['ordersn']);
            $consume_amount= floatval($order_info['actual_price']);
            $level_num = Model_Fenxiao::get_rank($fenxiao['memberid'],$order['memberid']);
            $fenxiao_model = ORM::factory('fenxiao')->where('memberid','=',$order['memberid'])->find();
            if (!$fenxiao_model->loaded())
            {
                continue;
            }
            $compute_info = Model_Member_Order_Compute::get_income_info($order['id']);

            if(!empty($fenxiao_data))
            {
                $cur_level_num = $order_info['memberid'] == $fenxiao['memberid']?'':$level_num;
                if($fenxiao_data['fx_status']!='-3' && $fenxiao_data['fx_status']!='1' && $cur_level_num=='')
                {
                    continue;
                }

                $cur_commission_type = $fenxiao_data['type'.$cur_level_num];

                if ($cur_commission_type == 1) {
                    $total += floatval($consume_amount * $fenxiao_data['fxratio'.$cur_level_num]);
                }
                else if($cur_commission_type==2)
                {
                    $total += floatval($compute_info['platform_commission'] * $fenxiao_data['pm_fxratio'.$cur_level_num]);
                }
                else {
                    if ($order['typeid'] == 1) {
                        $total += floatval($fenxiao_data['cash'.$cur_level_num]) * intval($order['dingnum']) + floatval($fenxiao_data['cash'.$cur_level_num.'_old']) * intval($order['oldnum']) + floatval($fenxiao_data['cash'.$cur_level_num.'_child']) * intval($order['childnum']);
                    } else {
                        $total += floatval($fenxiao_data['cash'.$cur_level_num]) * intval($order['dingnum']);
                    }
                    //$total += floatval($commission_info['cash_arr'][$index]);
                }

            }
            else
            {
                $commission_info = Model_Fenxiao::get_commission_info_line($order['typeid'], $order['productautoid'], $fenxiao['fxgroupid']);

                $index = $level_num - 1;
                if ($order_info['memberid'] == $fenxiao['memberid']) {
                    $index = 3;
                }
                if ($commission_info['commission_type'] == 1) {
                    $total += floatval($consume_amount * $commission_info['rate_arr'][$index]);
                } else if ($commission_info['commission_type'] == 2) {

                    $total += floatval($compute_info['platform_commission'] * $commission_info['pm_rate_arr'][$index]);
                } else {
                    $cash_info = $commission_info['cash_arr'][$index];

                    if ($order['typeid'] == 1) {
                        $total += floatval($cash_info['adult']) * intval($order['dingnum']) + floatval($cash_info['old']) * intval($order['oldnum']) + floatval($cash_info['child']) * intval($order['childnum']);
                    } else {
                        $total += floatval($cash_info['adult']) * intval($order['dingnum']);
                    }
                    //$total += floatval($commission_info['cash_arr'][$index]);
                }
            }

        }
        return $total;
    }

    //和Controller_Mobile_Fenxiao_Jieshao的函数一致
    public static function get_prospect_fenxiao_price($typeid,$product,$fxgroupid)
    {
        // $member_info = Model_Member_Login::check_login_info();
        // $fenxiao = DB::select()->from('fenxiao')->where('memberid','=',$member_info['mid'])->execute()->current();

        $commission_type=Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$typeid,$fxgroupid);
        $min_price = self::get_price($typeid,$product['id']);

        $product['price'] = empty($product['price'])?0:$product['price'];
        $min_price = is_array($min_price)?$min_price['price']:$min_price;
        $min_price = empty($min_price)?0:$min_price;
        $product['price'] = !empty($min_price)?$min_price:$product['price'];

        if($commission_type==1)
        {
            $commission_rate = Model_Fenxiao::get_commission_rate($typeid,$product['id'],$fxgroupid);
            $profit =number_format($product['price']*$commission_rate[0],2);
        }
        else if($commission_type==2)
        {
            $commission_rate = Model_Fenxiao::get_commission_rate_platform($typeid,$product['id'],$fxgroupid);


            $temp_order = array('typeid'=>$typeid,'productautoid'=>$product['id'],'totalprice'=>$product['price'],'dingnum'=>1);

            if($typeid==5)
            {

                $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
            }
            else
            {
                $platform_price = empty($product['supplierlist']) ? $product['price'] : Model_Member_Order_Compute::caculate_platform_commission($temp_order);
            }



            $profit = number_format($platform_price*$commission_rate[0],2);
        }
        else
        {
            $commission_cash = Model_Fenxiao::get_commission_cash_line($typeid,$product['id'],$fxgroupid);
            $profit =number_format($commission_cash[0]['adult'],2);
        }

        return $profit;
    }
}